<template>
  <div class="upload">
    <el-card>
      <h1>{{ name }}导入</h1>
      <ReadExcel
        :beforeUpload="beforeUpload"
        :onSuccess="onSuccess"
      ></ReadExcel>
    </el-card>
  </div>
</template>

<script>
import { sysUserBatch } from '@/api/employess.js'
export default {
  data () {
    return {
      name: this.$route.query.name
    }
  },
  methods: {
    beforeUpload (file) {
      console.log(file)
      return true
    },
    async onSuccess ({ header, results }) {
      // 创建对应字段关系
      const obj = {
        入职日期: 'timeOfEntry',
        姓名: 'username',
        工号: 'workNumber',
        手机号: 'mobile',
        转正日期: 'correctionTime'
      }
      //   map返回新数组 数组每一项都是对象
      const newArr = results.map(item => {
        //   声明空对象
        const temp = {}
        // 遍历  将obj属性值 替换result属性名
        Object.keys(item).forEach(v => {
          // [obj[v]]=obj属性值   item[v]= resluts属性名
          temp[obj[v]] = item[v]
          if (obj[v] === 'timeOfEntry' || obj[v] === 'correctionTime') {
            const t1 = new Date(
              (item[v] - 1) * 24 * 60 * 60 * 1000 - 8 * 60 * 60 * 1000
            )
            t1.setYear(t1.getFullYear() - 70)
            temp[obj[v]] = t1
          }
        })
        return temp
      })
      await sysUserBatch(newArr)
      this.$message.success('导入成功')
      this.$router.push(this.$route.query.redirect || '/employees')
      console.log(newArr)
    }
  }
}
</script>

<style lang="scss" scoped>
.upload {
  text-align: center;
  padding: 20px;
}
</style>
